package com.lovo.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.bean.*;
import com.lovo.config.RedisCacheUtil;
import com.lovo.dto.BuyerDto;
import com.lovo.dto.OrderDto;
import com.lovo.dto.OrderGoodsDto;
import com.lovo.mapper.SysOrderMapper;
import com.lovo.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * ????? 服务实现类
 * </p>
 *
 * @author lovo
 * @since 2022-09-17
 */
@Service
public class SysOrderServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder> implements ISysOrderService {


    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Autowired
    ISysCommodityService commodityService;

    @Autowired
    IAddressService addressService;


    @Autowired
    IOrdergoodsService ordergoodsService;

    @Autowired
    ISavemoneyService savemoneyService;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    FShopHDService fShopHDService;


    @Autowired
    MQService mqService;

    @Override
    public IPage<SysOrder> findAllOrderByUserId(Integer pageNO, Integer userId) {
        QueryWrapper<SysOrder> qw = new QueryWrapper<>();
        qw.eq("userId", userId);

        return this.getBaseMapper().selectPage(new Page<>(pageNO, 5), qw);
    }

    @Override
    @Transactional
    public boolean buyCar(Integer userId, Integer addressId, String buyType) {
        String userKey = String.valueOf(userId);
        int allPrice = 0;
        List<Ordergoods> ordergoodsList = new ArrayList<>();
        if (redisCacheUtil.hasKey(userKey)) {
            Set<Object> set = redisCacheUtil.hashGetFileds(userKey);

            for (Object obj : set) {
                //获得Map的key
                String mapKey = String.valueOf(obj);
                //获取购物车商品对象
                BuyerDto buyerDto = JSON.parseObject(JSON.toJSONString(redisCacheUtil.hget(userKey, mapKey)), BuyerDto.class);
                System.err.println(buyerDto);
                //获取到对象后 调取商城后端接口 扣除商品库存  true 存入订单  失败不加订单
                boolean flag = fShopHDService.sellProduct(buyerDto.getProductId(), buyerDto.getNum());
                if (flag) {
                    //查询 出库存商品信息
                    SysCommodity sysCommodity = commodityService.getBaseMapper().selectById(buyerDto.getProductId());
                    //吧库存商品信息放入订单商品中
                    Ordergoods ordergoods = new Ordergoods();
                    ordergoods.setGoodsname(buyerDto.getProductName());
                    ordergoods.setOBatch(sysCommodity.getPBatch());
                    ordergoods.setONum(buyerDto.getNum());
                    ordergoods.setOPrice(sysCommodity.getPPrice());
                    allPrice += ordergoods.getONum() * sysCommodity.getPPrice();
                    ordergoodsList.add(ordergoods);
                }

            }
        } else {
            return false;
        }

        SysUser sysUser = sysUserService.getBaseMapper().selectById(userId);
        if (buyType.equals("1")) {
            if (sysUser.getSavemoney() < allPrice) {
                return false;
            }
            sysUser.setSavemoney(sysUser.getSavemoney() - allPrice);
            sysUserService.getBaseMapper().updateById(sysUser);
        }

        //清空购物车
        redisCacheUtil.del(userKey);


        Address address = addressService.getBaseMapper().selectById(addressId);

        SysOrder sysOrder = new SysOrder();
        sysOrder.setPersonname(address.getReceiver());
        sysOrder.setSAddress(address.getArea() + "," + address.getFulladdress());
        sysOrder.setUserid(userId);
        sysOrder.setSStatus("已完成");
        sysOrder.setSMoney(allPrice);

        this.getBaseMapper().insert(sysOrder);
        //将订单用mq发送给后端
        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(sysOrder, orderDto);

        mqService.sendOrder(orderDto);

        List<OrderGoodsDto> orderGoodsDtoList = new ArrayList<>();
        ordergoodsList.forEach(n -> {
            n.setOrderid(sysOrder.getSaleid());
            ordergoodsService.getBaseMapper().insert(n);

            OrderGoodsDto orderGoodsDto = new OrderGoodsDto();
            BeanUtils.copyProperties(n, orderGoodsDto);
            orderGoodsDtoList.add(orderGoodsDto);

        });
        //将商品订单 信息 mq发送至后端。
        mqService.sendSellGoods(orderGoodsDtoList);

        Savemoney savemoney = new Savemoney();
        savemoney.setUserid(userId);
        savemoney.setSavestatus("支出");
        savemoney.setSalemoney(allPrice);
        savemoneyService.getBaseMapper().insert(savemoney);


        return true;
    }

    @Override
    public boolean addOrder(Integer userId, Integer addressId, String buyType, Integer productId, Integer num) {
        // 调取商城后端接口 扣除商品库存  true 存入订单  失败不加订单
        boolean flag = fShopHDService.sellProduct(productId, num);
        if (!flag) {
            return false;
        }
        SysCommodity sysCommodity = commodityService.getBaseMapper().selectById(productId);

        int allPrice = sysCommodity.getPPrice() * num;

        SysUser user = sysUserService.getBaseMapper().selectById(userId);
        if (buyType.equals("1")) {
            if (user.getSavemoney() < allPrice) {
                return false;
            }
            user.setSavemoney(user.getSavemoney() - allPrice);
            sysUserService.getBaseMapper().updateById(user);
        }


        Address address = addressService.getBaseMapper().selectById(addressId);

        SysOrder sysOrder = new SysOrder();
        sysOrder.setPersonname(address.getReceiver());
        sysOrder.setSAddress(address.getArea() + "," + address.getFulladdress());
        sysOrder.setUserid(userId);
        sysOrder.setSStatus("已完成");
        sysOrder.setSMoney(allPrice);

        this.getBaseMapper().insert(sysOrder);

        //将订单用mq发送给后端
        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(sysOrder, orderDto);
        mqService.sendOrder(orderDto);
//添加订单商品表
        Ordergoods ordergoods = new Ordergoods();
        ordergoods.setOrderid(sysOrder.getSaleid());
        ordergoods.setONum(num);
        ordergoods.setGoodsname(sysCommodity.getPName());
        ordergoods.setOPrice(sysCommodity.getPPrice() * num);
        ordergoods.setOBatch(sysCommodity.getPBatch());
        ordergoods.setOSize("555");

        ordergoodsService.getBaseMapper().insert(ordergoods);

        List<OrderGoodsDto> orderGoodsDtoList = new ArrayList<>();
        OrderGoodsDto orderGoodsDto = new OrderGoodsDto();
        BeanUtils.copyProperties(ordergoods, orderGoodsDto);
        orderGoodsDtoList.add(orderGoodsDto);
        //将商品订单 信息 mq发送至后端。
        mqService.sendSellGoods(orderGoodsDtoList);


        Savemoney savemoney = new Savemoney();
        savemoney.setUserid(userId);
        savemoney.setSavestatus("支出");
        savemoney.setSalemoney(allPrice);
        savemoneyService.getBaseMapper().insert(savemoney);

        return true;
    }


}
